package com.zxh.listdemo.adapter.list.common;

import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.View;
import android.view.ViewGroup;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangxuehui on 2018/2/28.
 */

public abstract class BaseMultiListAdapter<M extends BaseMultiModel> extends BaseListAdapter<M> {
    private Map<Integer, BaseViewHolder> mHolders;
    private SparseIntArray mLayoutIds;

    public BaseMultiListAdapter(@Nullable List<M> mList) {
        super(mList);
        mHolders = new HashMap<>();
        mLayoutIds = new SparseIntArray();
        addLayoutIds();
    }

    protected abstract void addLayoutIds();

    protected void addLayoutId(@NonNull int itemType, @LayoutRes int layoutId) {
        mLayoutIds.append(itemType, layoutId);
    }


    @Override
    public int getItemViewType(int position) {
        return mList.get(position).getItemType();
    }

    @Override
    public int getViewTypeCount() {
        return mLayoutIds.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        int itemType = getItemViewType(position);
        BaseViewHolder holder;
        if (mHolders.get(itemType) == null) {
            holder = BaseViewHolder.getViewHolder(convertView, parent, getLayoutId(itemType));
            mHolders.put(itemType, holder);
        } else {
            holder = mHolders.get(itemType);
        }
        convert(holder, position);
        return holder.getConvertView();
    }

    /**
     * 通过数据类型，获取布局id
     *
     * @param itemType
     * @return
     */
    protected int getLayoutId(int itemType) {
        return mLayoutIds.get(itemType);
    }

    /**
     * 检查数据的类型
     *
     * @param position 位置
     * @param cls      类class 用于判断是否是同一个class对像
     * @return
     */
    public boolean checkTypeForModel(int position, Class cls) {
        return getItem(position) != null && cls.equals(getItem(position).getClass());
    }
}
